package com.pingan.haofang.searchcloud.common.redis.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pingan.haofang.searchcloud.common.redis.RedisQueueListener;
import com.pingan.haofang.searchcloud.index.constants.IndexBuildConstants;
import com.pingan.haofang.searchcloud.index.dto.IndexBuildIncDTO;
import com.pingan.haofang.searchcloud.index.service.IndexBuildService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicLong;

/**
 * TODO: 请添加描述
 *
 * @author liujunjun380
 * @date 2018/11/19
 * @since 1.0.0
 */
@Service
public class QueueListener implements RedisQueueListener<String> {
    static Logger LOG = LoggerFactory.getLogger(QueueListener.class);

    @Autowired
    private IndexBuildService indexBuildService;

    private Gson GSON = new GsonBuilder().serializeNulls().setLenient().create();

    private static AtomicLong num  = new AtomicLong(0);
    private static AtomicLong totaltime = new AtomicLong(0);
    private static AtomicLong mintime = new AtomicLong(99999999999999L);
    private static AtomicLong maxtime = new AtomicLong(0);


    @Override
    public void onMessage(String dto) {
        Long begin = System.currentTimeMillis();
        IndexBuildIncDTO indexBuildIncDTO = GSON.fromJson(dto, IndexBuildIncDTO.class);
        indexBuildService.executeIndexInc(indexBuildIncDTO);
        long end = System.currentTimeMillis() - begin;

        long currentTime = totaltime.addAndGet(end);
        long currentNum = num.incrementAndGet();
        if(end > maxtime.get()) {
            maxtime.getAndSet(end);
        }
        if(end < mintime.get()) {
            mintime.getAndSet(end);
        }

        LOG.info("inc-msg-consumed, redis key:{}:{}_{}, cost:{}(ms),avg-cost:{}(ms), max:{}(ms),min:{}(ms),total:{}(ms),num:{},info:{}", IndexBuildConstants.INDEX_INC_KEY_PERFIX,
                indexBuildIncDTO.getProjectCode(), indexBuildIncDTO.getIndexName(), end,currentTime/currentNum, maxtime.get(),mintime.get(),totaltime.get(),num.get(),indexBuildIncDTO);
    }
}
